

# 自定义登录接口返回信息,在settings里配置
# 返回什么，前端就看到什么
from rest_framework_jwt.utils import jwt_decode_handler

from api import models


# 自定义登录接口返回信息,在settings里配置
# 返回什么，前端就看到什么
def my_jwt_response_payload_handler(token, user=None, request=None):
    """
    Returns the response data for both the login and refresh views.
    Override to return a custom response such as including the
    serialized representation of the User.

    Example:

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request': request}).data
        }

    """
    return {
        'token': token,
        'msg': '登录成功',
        'status': 100,
        'username': user.username
    }


# 两种方式自定制基于jwt的认证类
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt


class MyJwtAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 首先获取token值
        jwt_value = request.META.get('HTTP_AUTHORIZATION')
        if jwt_value:
            try:
                # jwt提供了通过三段token，取出payload的方法，并且有校验功能
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                raise AuthenticationFailed('签名已过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('非法用户,未携带token信息')
            except Exception as e:
                print(e)
                raise AuthenticationFailed(str(e))
            print(payload)  # 用户信息字典
            # return jwt_value, jwt_value
            # 将用户信息字典转成user对象
            # 第一种，去数据库查
            # user = models.User.objects.filter(pk=payload.get('user_id')).first()
            user = models.User(id=payload.get('user_id'), username=payload.get('username'))
            return user, jwt_value
        # 么有jwt值抛异常
        raise AuthenticationFailed('请携带认证信息')


class MyJwtAuthentication2(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        # 首先获取token值
        jwt_value = request.META.get('HTTP_AUTHORIZATION')
        if jwt_value:
            try:
                # jwt提供了通过三段token，取出payload的方法，并且有校验功能
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                raise AuthenticationFailed('签名已过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('非法用户,未携带token信息')
            except Exception as e:
                print(e)
                raise AuthenticationFailed(str(e))
            print(payload)  # 用户信息字典
            user = self.authenticate_credentials(payload=payload)
            return user, jwt_value
        # 么有jwt值抛异常
        raise AuthenticationFailed('请携带认证信息')




